const path = require('path');
const webpack = require('webpack');
const Dotenv = require('dotenv-webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

// console.log(process.env);
// console.log({ NODE_ENV: process.env.NODE_ENV, prod: process.env.production });
const devMode = process.env.NODE_ENV !== 'production';
// new MiniCssExtractPlugin({
//   filename: devMode ? "[name].css" : "[name].[contenthash].css",
//   chunkFilename: devMode ? "[id].css" : "[id].[contenthash].css",
// })

module.exports = {
  entry: {
    index: './src/index.js',
  },
  optimization: {
    moduleIds: 'hashed',
    runtimeChunk: 'single',
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
        },
      },
    },
  },
  output: {
    filename: '[hash:8].[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: 'i___dex',
    }),
    new Dotenv(),
  ],
  module: {
    noParse: /loadash/,
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
          },
        },
      },
      {
        test: /\.css$/,
        include: path.resolve(__dirname, 'src'),
        use: [
          devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: { plugins: { autoprefixer: {} } },
            },
          },
        ],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192,
              fallback: {
                loader: 'file-loader',
                options: {
                  // publicPath: 'assets',
                  outputPath: 'images',
                  name: '[name].[contenthash:8].[ext]',

                  // name() {
                  //   if (process.env.NODE_ENV === 'development') {
                  //     return '[path][name].[ext]';
                  //   }
                  //   return 'img/[name].[contenthash:8].[ext]';
                  // },
                },
              },
            },
          },
        ],
        // loader: 'file-loader',
        // options: {
        //   name: '[hash:8]-[name].[ext]',
        // },
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: ['file-loader'],
      },
      {
        test: /\.txt$/i,
        use: [
          {
            loader: 'raw-loader',
            options: {
              esModule: false,
            },
          },
        ],
      },
    ],
  },
};
